package com.dingding.common.core.im.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.dingding.common.core.im.IInstantMessenger;
import com.dingding.common.core.im.dto.FormatType;
import com.dingding.common.core.im.dto.SdkHttpResult;
import com.dingding.common.core.im.util.HttpUtil;
import com.dingding.common.core.util.JSONUtil;

/**
 * @ClassName: InstantMessengerImpl
 * @Description: 融云通知实现类
 * @author yuHaiQing
 * @date 2016年3月30日 下午4:58:43
 */
public class InstantMessengerImpl implements IInstantMessenger {

	// 开发者平台分配的 App Key
	private static String appKey = "x18ywvqf8g8cc";
	// 开发者平台分配的 App Secret
	private static String appSecret = "jbCjSYnc3EC";
	// 融云服务地址
	private static final String RONGCLOUDURI = "http://api.cn.ronghub.com";
	// 字符
	private static final String UTF8 = "UTF-8";

	/**
	 * @Title: getToken 
	 * @Description: 获取Token
	 * @param userId 叮叮搭车用户Id
	 * @param userName 叮叮搭车用户名称
	 * @param portraitUri 叮叮搭车用户头像
	 * @param format 请求格式(JSON/XML)
	 * @author yuHaiQing
	 * @return SdkHttpResult    返回类型
	 * @throws IOException 
	 * @throws ProtocolException 
	 * @throws MalformedURLException 
	 */
	public String getToken(String userId, String userName, String portraitUri, FormatType format) {

		try {
			HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret,
					RONGCLOUDURI + "/user/getToken." + format.toString());

			StringBuilder sb = new StringBuilder();
			sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
			sb.append("&name=").append(URLEncoder.encode(userName == null ? "" : userName, UTF8));
			sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri == null ? "" : portraitUri, UTF8));
			HttpUtil.setBodyParameter(sb, conn);

			// 获取请求融云服务器返回参数
			SdkHttpResult sdkHttpResult = HttpUtil.returnResult(conn);

			// 判断请求融云服务器注册Token是否成功
			if (sdkHttpResult.getHttpCode() == 200) {

				// 将返回的字符串转为JSON格式
				JSONObject jsonObject = JSONUtil.parseObject(sdkHttpResult.getResult());

				// 获取返回的Token值
				return jsonObject.get("token").toString();
			}

			return null;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
